package org.jradweb.tools.generator.freemarker;

import java.io.File;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.Column;

import org.apache.maven.plugin.logging.Log;
import org.jradweb.tools.generator.FileAlreadyExistsException;
import org.jradweb.tools.generator.FileOperatorException;
import org.jradweb.tools.generator.FreemarkerTemplateExcepion;
import org.jradweb.tools.generator.freemarker.util.FileGenerator;
import org.jradweb.tools.generator.freemarker.util.Templates;
import org.jradweb.tools.generator.utils.LogImpl;

public class DatasetGenerator extends ClassGenerator {
	private String dataSetPath;
	private String classPath;

	public DatasetGenerator(File projectRootPath, String groupId,
			String artifactId, Log log) {
		super(projectRootPath, groupId, artifactId, log);

		dataSetPath = projectRootPath.getAbsolutePath()
				+ "/src/test/resources/dataset/";
		classPath = projectRootPath.getAbsolutePath() + "/target/classes/";

	}

	public boolean createDatasetFile(String modelName)
			throws FileOperatorException, FileAlreadyExistsException,
			FreemarkerTemplateExcepion ,ClassNotFoundException{
		Value model = new Value(modelName);

		File path = new File(this.dataSetPath);
		if (!path.exists()) {
			path.mkdirs();
		}

		File lastFile = null;
		File[] files = path.listFiles();
		for (File file : files) {
			String fileName = file.getName();
			if (fileName.matches("[0-9]{1,5}_[a-z,A-Z]{1,100}\\.xml")) {
				lastFile = file;
			}
		}
		String fileName;
		if (lastFile == null) {
			fileName = "0001_" + model.getName() + ".xml";
		} else {
			String sfn=lastFile.getName().substring(0, 4);
			int fn=Integer.parseInt(sfn);
			fn++;
			if(fn<10)
				fileName="000"+fn+"_"+model.getName()+".xml";
			else if(fn<100){
				fileName="00"+fn+"_"+model.getName()+".xml";
			}
			else if(fn<1000){
				fileName="0"+fn+"_"+model.getName()+".xml";
			}
			else
			{
				fileName=fn+"_"+model.getName()+".xml";
			}
		}
		
		File file=new File(this.dataSetPath+fileName);
		
		
	
		params.put("model", model);
		try {
			params.put("props", this.getProperties(model));
		} catch (ClassNotFoundException e1) {
			throw e1;
		}
		
		try {
			FileGenerator.writeFile(file, params,
					Templates.DATASET_TEMPLATE, false);
		} catch (FileAlreadyExistsException e) {
			log.warn("File " + file.getAbsolutePath()
					+ " already exists!");
			return false;
		}

		log.info("File " + file.getAbsolutePath()
				+ " created successfully!");

		return true;
	}

	
	private List<Value> getProperties(Value model) throws ClassNotFoundException{
		URL url = null;
		Class modelClass = null;
		List<Value> columns = new ArrayList<Value>();
		try {
			url = new URL("file:" + classPath);

			ClassLoader loader = Thread.currentThread().getContextClassLoader();
			URLClassLoader ucl = new URLClassLoader(new URL[] { url }, loader);

			String className = this.groupId + "." + this.artifactId + ".model."
					+ model.getName();
			modelClass = ucl.loadClass(className);
			columns = this.getProperties(modelClass);
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (ClassNotFoundException e) {
			throw e;
		}

		return columns;
	}

	private List<Value> getProperties(Class modelClass) {
		List<Value> values = new ArrayList<Value>();
		for (Method method : modelClass.getMethods()) {
			if (method.getAnnotation(Column.class) != null) {
				if (!method.getName().equals("getCreatedAt")
						&& !method.getName().equals("getUpdatedAt")) {
					String name = method.getName().substring(3);
					values.add(new Value(name));
				}
			}
		}
		return values;
	}

	public static void main(String[] args) {

		String model = "Customer";

		try {
			File projectRootPath = new File("D:/workspace2/jradtest");
			DatasetGenerator cg = new DatasetGenerator(projectRootPath,
					"org.jradweb", "jradtest",
					new LogImpl(ClassGenerator.class));
			// cg.createModelClass(model);
			// cg.createDao(model);
			// cg.createDaoImpl(model);
			// cg.createService(model, model,true);
			// cg.createAbstractService(model, model,true);
			// cg.createServiceImpl(model, model, true);
			// cg.createController(model, model, model,true);
			//			
			cg.createDatasetFile("customer");
		} catch (FileOperatorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileAlreadyExistsException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
